package com.kuding.config;

import static java.util.stream.Collectors.groupingBy;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.aliyun.openservices.loghub.client.ClientWorker;
import com.aliyun.openservices.loghub.client.interfaces.ILogHubProcessorFactory;
import com.kuding.config.conditional.ConditionalOnEnableAliyun;
import com.kuding.enums.WhatDoWeHave;
import com.kuding.log.components.LogWorkerContainer;
import com.kuding.log.interfaces.VinusLogHubProcessorFactory;
import com.kuding.log.interfaces.VinusLogProcessAdpter;
import com.kuding.props.AliyunLogProperties;

@Configuration
@ConditionalOnEnableAliyun(WhatDoWeHave.LOG)
@EnableConfigurationProperties({ AliyunLogProperties.class })
@ConditionalOnClass(ClientWorker.class)
public class AliyunLogConfig {

	@Autowired
	private AliyunLogProperties aliyunLogProperties;

	@Autowired
	private ExecutorService vinusLogThreadExecutor;

	private final Log logger = LogFactory.getLog(AliyunLogConfig.class);

	@Bean
	@ConditionalOnMissingBean
	public VinusLogHubProcessorFactory logHubProcessorFactory(
			@Autowired(required = false) List<VinusLogProcessAdpter> list) {
		logger.debug("discover logProcessors:" + list);
		Map<String, List<VinusLogProcessAdpter>> processAdapterMap = list == null ? Collections.emptyMap()
				: list.stream().collect(groupingBy(VinusLogProcessAdpter::getGroup));
		return new VinusLogHubProcessorFactory(processAdapterMap);
	}

	@Bean
	public LogWorkerContainer LogWorkerContainer(ILogHubProcessorFactory logHubProcessorFactory) {
		return new LogWorkerContainer(aliyunLogProperties, vinusLogThreadExecutor, logHubProcessorFactory);
	}

}
